package com.lu.manage.modular.generate.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lu.manage.core.tips.ErrorTip;
import com.lu.manage.core.tips.SuccessTip;
import com.lu.manage.core.utils.ObjectConvertUtil;
import com.lu.manage.modular.generate.model.CodeStrategy;
import com.lu.manage.modular.generate.service.GeneratorCodeService;
import com.lu.manage.modular.system.service.DatasourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.util.Map;

/**
 * @program sKnowledge_Blog
 * @description: 代码生成工具
 * @author: zhanglu
 * @create: 2019-07-14 16:20:00
 */
@Controller
@RequestMapping("/generate/code")
public class GeneratorCodeController {

    private static String PREFIX = "/modular/generate/code";

    @Autowired
    private GeneratorCodeService generatorCodeService;

    @Autowired
    private DatasourceService datasourceService;

    @RequestMapping("")
    public String index(){
        return PREFIX + "/index.html";
    }

    /**
     * 获取表信息
     */
    @GetMapping("/get")
    @ResponseBody
    public Object get(String datasourceId){
        try {
            return generatorCodeService.get(datasourceId);
        } catch (Exception e) {
            e.printStackTrace();
            return new ErrorTip(-1, e + "");
        }
    }

    /**
     * 数据源列表
     * @param map
     * @return
     */
    @GetMapping("/select")
    @ResponseBody
    public Object select(@RequestParam Map<String, Object> map){
        return new SuccessTip(ObjectConvertUtil.select(JSONArray.parseArray(JSON.toJSONString(datasourceService.list(map)), Map.class)));
    }

    /**
     * 构建
     */
    @GetMapping("/execute")
    public void execute(String data, String datasourceId, HttpServletResponse response) throws Exception{
        data = URLDecoder.decode(data, "UTF-8");
        CodeStrategy codeStrategy = JSONObject.parseObject(data, CodeStrategy.class);
        generatorCodeService.execute(response, codeStrategy, datasourceId);
    }

}
